// Learn cc.Class:
//  - [Chinese] http://docs.cocos.com/creator/manual/zh/scripting/class.html
//  - [English] http://www.cocos2d-x.org/docs/creator/en/scripting/class.html
// Learn Attribute:
//  - [Chinese] http://docs.cocos.com/creator/manual/zh/scripting/reference/attributes.html
//  - [English] http://www.cocos2d-x.org/docs/creator/en/scripting/reference/attributes.html
// Learn life-cycle callbacks:
//  - [Chinese] http://docs.cocos.com/creator/manual/zh/scripting/life-cycle-callbacks.html
//  - [English] http://www.cocos2d-x.org/docs/creator/en/scripting/life-cycle-callbacks.html
var ImgSplit = require("ImgSplit");
var Root = require("Root");

cc.Class({
    extends: cc.Component,

    properties: {
        // foo: {
        //     // ATTRIBUTES:
        //     default: null,        // The default value will be used only when the component attaching
        //                           // to a node for the first time
        //     type: cc.SpriteFrame, // optional, default is typeof default
        //     serializable: true,   // optional, default is true
        // },
        // bar: {
        //     get () {
        //         return this._bar;
        //     },
        //     set (value) {
        //         this._bar = value;
        //     }
        // },
    },

    // LIFE-CYCLE CALLBACKS:

    onLoad() {
        //  this.isHave = [];//滑轮位置是否有空的位置
        this.startpuzzle = [];//所有物体组成的数组
        this.BGisHave = [];
        this.AllCorrectArray = [];
        this.correctArray = [];
        this.LockArray = [];
        this.puzzleBG2 = [];
        this.startpos = [];
        this.root = cc.find("root").getComponent(Root);
        this.row = this.root.row;
        this.column = this.root.column;
        //this.useless = this.root.waste;//废片数量
        this.useless = Math.floor(Math.random() * (this.column + 1));         //废片数量
        this.mask = cc.find("Canvas/Mask");
        this.contentMask = cc.find("Canvas/ContentMask");
        this.repeatLabel = cc.find("Canvas/repeatLabel");
        this.repeatButton = cc.find("Canvas/repeatButton");
        this.winLabel = cc.find("Canvas/WinLabel");
        this.puzzleBGNode = cc.find("Canvas/PuzzleBG");
        this.movePart = cc.find("Canvas/MovePart");
        this.lockPart = cc.find("Canvas/LockPart");
        this.scrollView = cc.find("Canvas/PuzzleChooseScrollView");
        this.content = cc.find("Canvas/PuzzleChooseScrollView/view/content");
        this.contentBG = cc.find("Canvas/contentbg");
        this.puzzleBG2 = [];
        this.isLock = [];
        this.puzzlebgChildren = [];
        this.spine = null;
        this.yellow = cc.find("Canvas/yellow");
        this.black = cc.find("Canvas/black");
        this.animNum = [];
        this.curanim = [];
        this.lightAtlas_48 = null;
        this.lightAtlas_24 = null;
        this.shadow = [];
        this.slideOver = false;
        this.dontOnMask = null;
        this.donContOnMask = null;
        this.completePic = new cc.Node("over");
        this.picPre = new cc.Node("tint");

        console.log(this.picPre);

        console.log(this.puzzleBG2);

        this.content.width = (this.row * this.column + this.useless) * 200;
        for (let i = 0; i < this.row * this.column + this.useless; i++) {
            this.startpos.push(cc.v2(100 + 200 * i, -120));
        }
        console.log(this.content.width);
        // cc.find("Canvas/PuzzleChooseScrollView/view/content/1").parent = cc.find("Canvas/PuzzleChooseScrollView/view/content/2");
        // for (let i = 1; i <= this.row * this.column + this.useless; i++) {

        //     this.isHave.push(true);
        // }
        // for (let i = 1; i <= this.row * this.column + this.useless; i++) {
        //     this.startpuzzle.push(children[i - 1]);
        // }
        // for (let i = 1; i <= 9; i++) {
        //     this.startpuzzle.push(cc.find("Canvas/PuzzleChooseScrollView/view/content/" + i));
        // }
        for (let i = 0; i < this.row; i++) {
            this.BGisHave.push([]);

            for (let j = 0; j < this.column; j++) {
                this.BGisHave[i].push([]);
            }
        }
        for (let i = 0; i < this.row; i++) {
            this.isLock.push([]);
            for (let j = 0; j < this.column; j++) {
                this.isLock[i].push(false);
            }
        }

        this.scrollView.on('scroll-ended', function (event) {
            console.log("jjjjjjj");
            for (let i = 0; i < this.shadow.length; i++) {
                this.shadow[i].destroy();
            }
            this.shadow.splice(0, this.shadow.length);
            this.slideOver = true;
            this.dontOnMask.parent = null;
            this.donContOnMask.parent = null;


        }.bind(this));
        // for (let i = 0; i < cc.imgSplit.spriteArray.length; i++) {
        //     this.puzzlebgChildren.push(cc.imgSplit.spriteArray[i].node);
        // }
        // console.log(this.puzzlebgChildren);
        // for (let i = 0; i < this.row; i++) {
        //     this.puzzleBG2.push([]);
        //     for (let j = 0; j < this.column; j++) {
        //         this.puzzleBG2[i].push(this.puzzlebgChildren[j]);

        //     }
        //     this.puzzlebgChildren.splice(0, this.column);
        // }
        // for (let i = 0; i < this.puzzleBGNode.getChildren().length; i++) {
        //     this.puzzlebgChildren.push(this.puzzleBGNode.getChildren()[i]);
        // }
        // for (let i = 0; i < this.row; i++) {
        //     this.puzzleBG2.push([]);
        //     for (let j = 0; j < this.column; j++) {
        //         this.puzzleBG2[i].push(this.puzzlebgChildren[j]);

        //     }
        //     this.puzzlebgChildren.splice(0, this.column);
        // }
        // console.log(this.puzzleBG2);
    },

    start() {
        //console.log("start");
        var self = this;

        console.log(this.row);
        //this.useless = 0;
        cc.imgSplit = new ImgSplit(this.row, this.column, this.useless);
        cc.loader.loadRes("Spine/magic", cc.Prefab, function (err, prefab) {
            self.spine = cc.instantiate(prefab);
            console.log(self.spine);
        });
        cc.loader.loadResDir("Animation/round0", cc.Prefab, function (err, anims) {
            // for (let i = 0; i < anims.length - 1; i++) {
            //     if (Number(anims[i].name[anims[i].name.length - 1]) > Number(anims[i + 1].name[anims[i + 1].name.length - 1])) {
            //         let temp = anims[i + 1];
            //         anims[i + 1] = anims[i];
            //         anims[i] = temp;
            //     }

            // }
            // self.curanim = anims;
            for (let i = 0; i < anims.length; i++) {
                let index = Number(anims[i]._name.split('_')[1]);
                self.curanim[index] = cc.instantiate(anims[i]);
            }

            console.log(self.curanim);
        });
        cc.loader.loadRes("DontOnMask", cc.prefab, function (err, mask) {

            self.dontOnMask = cc.instantiate(mask);


        });
        cc.loader.loadRes("DonContOnMask", cc.prefab, function (err, mask) {

            self.donContOnMask = cc.instantiate(mask);
            console.log(self.donContOnMask);

        });
        //2019-1-8 读取网络图片，测试功能
        if (this.root.net) {
            console.log("走的哪里");
            if (!cc.localImage) {
                //var url = "http://106.12.147.168:8000/AmazingPuzzleImage/" + this.root.kindPuzzle + "/" + this.root.index + ".png";       //百度云测试服务器，较慢
                var url = "http://crazyfind-static.boomegg.cn/PuzzleImage/" + this.root.kindPuzzle + "/" + this.root.index + ".png";        //爆弹测试服务器
                // cc.loader.onProgress = function (completeCount, totalCount, item) {
                //     console.log("atrat加载了多少：" + completeCount);
                //     console.log("atawt拢共有多少：" + totalCount);
                // };
                cc.loader.load(url, function (err, pic) {
                        if (err) {
                            console.log("失败");
                            cc.log(err);
                        }
                        else {
                            console.log("成功")
                            //let pic = cc.find("Canvas/texture").getComponent(cc.Sprite).spriteFrame.getTexture();    //本地资源测试
                            cc.find("Canvas/ArticleToRead").active=false;
                            console.log(pic);
                            // var newNode = new cc.Node("test");
                            // newNode.parent = cc.find("Canvas");
                            // newNode.addComponent(cc.Sprite).spriteFrame = new cc.SpriteFrame(data);
                            self.picPre.addComponent(cc.Sprite).spriteFrame = new cc.SpriteFrame(pic);
                            console.log("停1");
                            self.picPre.parent = cc.find("Canvas/GameBG");
                            self.picPre.setPosition(cc.v2(0, 107));
                            self.picPre.color = new cc.Color(163, 163, 163);
                            self.picPre.opacity = 150;
                            self.picPre.active = false;
                            console.log("停2");
                            cc.imgSplit.startLevel(pic);
                            console.log("走完了吗");
                        }
                    }.bind(this));
            }
            else {
                console.log("成功")
                let pic = cc.find("Canvas/texture").getComponent(cc.Sprite).spriteFrame.getTexture();    //本地资源测试

                console.log(pic);
                // var newNode = new cc.Node("test");
                // newNode.parent = cc.find("Canvas");
                // newNode.addComponent(cc.Sprite).spriteFrame = new cc.SpriteFrame(data);
                self.picPre.addComponent(cc.Sprite).spriteFrame = new cc.SpriteFrame(pic);
                console.log("停1");
                self.picPre.parent = cc.find("Canvas/GameBG");
                self.picPre.setPosition(cc.v2(0, 107));
                self.picPre.color = new cc.Color(163, 163, 163);
                self.picPre.opacity = 150;
                self.picPre.active = false;
                console.log("停2");
                cc.imgSplit.startLevel(pic);
                console.log("走完了吗");
            }

        }
        else {
            cc.loader.loadRes("CompletePic/" + self.root.kindPuzzle + "/" + self.root.index + "Pic", cc.SpriteFrame, function (err, pic) {
                console.log(pic);


                self.picPre.addComponent(cc.Sprite).spriteFrame = pic;

                self.picPre.parent = cc.find("Canvas/GameBG");
                self.picPre.setPosition(cc.v2(0, 107));
                self.picPre.color = new cc.Color(163, 163, 163);
                self.picPre.opacity = 150;
                self.picPre.active = false;
                cc.imgSplit.start();


            })
        }



        cc.loader.loadRes("Atlas/light_48", cc.SpriteAtlas, function (err, atlas) {
            self.lightAtlas_48 = atlas;
            // for (let i = 0; i < 48; i++) {
            //     self.lightAtlas.getSpriteFrame(i.toString()).opacity = 0;
            // }
            //console.log(self.lightAtlas);
        });

        cc.loader.loadRes("Atlas/light_24", cc.SpriteAtlas, function (err, atlas) {
            self.lightAtlas_24 = atlas;
            // for (let i = 0; i < 48; i++) {
            //     self.lightAtlas.getSpriteFrame(i.toString()).opacity = 0;
            // }
            // console.log(self.lightAtlas);
        });

        cc.find("Canvas/yellow").setScale(0, 0);
        cc.find("Canvas/black").setScale(0, 0);
        cc.find("Canvas/WinLabel").setScale(0, 0);

    },
    repeatGame() {
        console.log(this.root.index);
        if (this.root.currentPageIndex == 0) {
            this.root.kindPuzzle = "Crocodile";
            console.log(this.root.index);
            this.root.index++;
            console.log(this.root.index);

            if (this.root.index == 7) {
                cc.director.loadScene("puzzleMain");
            }
            else {
                cc.director.loadScene("puzzle");

            }

        }
        else if (this.root.currentPageIndex == 1) {
            this.root.kindPuzzle = "Others";
            this.root.index++;
            if (this.root.index == 3) {
                cc.director.loadScene("puzzleMain");
            }
            else {
                cc.director.loadScene("puzzle");

            }

        }
        else if (this.root.currentPageIndex == 2) {
            this.root.kindPuzzle = "SmallRedCap";
            this.root.index++;
            if (this.root.index == 4) {
                cc.director.loadScene("puzzleMain");
            }
            else {
                cc.director.loadScene("puzzle");

            }

        }
        else if (this.root.currentPageIndex == 3) {
            this.root.kindPuzzle = "Terror";
            this.root.index++;
            if (this.root.index == 5) {
                cc.director.loadScene("puzzleMain");
            }
            else {
                cc.director.loadScene("puzzle");

            }

        }
        // cc.find("Canvas/Mask").active = false;
        // cc.find("Canvas/repeatLabel").active = false;
        // cc.find("Canvas/repeatButton").active = false;
    },
    backToMain() {
        cc.director.loadScene("puzzleMain");
    },
    helpClick() {
        console.log(this.root.kindPuzzle);
        console.log(this.root.index);
        var self = this;
        if (self.picPre.active == false) {
            self.picPre.active = true;
        }
        else {
            self.picPre.active = false;
        }

    },
    DontRoatate() {
        this.movePart.addChild(this.dontOnMask);
        this.content.addChild(this.donContOnMask);
        console.log(cc.imgSplit.spriteArray);
        this.root.isRotate = false;
        for (let i = 0; i < cc.imgSplit.spriteArray.length; i++) {
            for (let j = 0; j < cc.imgSplit.spriteArray[i].length; j++) {
                cc.imgSplit.spriteArray[i][j].node.rotation = 0;
            }

        }
        for (let i = 0; i < cc.imgSplit.useless.length; i++) {
            cc.imgSplit.useless[i].node.rotation = 0;
        }
        setTimeout(() => {
            this.dontOnMask.parent = null;
            this.donContOnMask.parent = null;
        }, 0);
    },
    destroyWaste() {
        console.log(cc.imgSplit.useless);
        cc.find("Canvas/DestroyWasteButton").getComponent(cc.Button).interactable = false;
        this.movePart.addChild(this.dontOnMask);
        this.content.addChild(this.donContOnMask);
        console.log(this.content.x);
        for (let i = 0; i < cc.imgSplit.useless.length; i++) {
            // cc.imgSplit.useless[i].parent = this.content;
            let action = null;
            if (cc.imgSplit.useless[i].node.parent == this.content) {
                action = cc.moveTo(1.5, cc.v2(-this.content.x, 480));
            }
            else {
                action = cc.moveTo(1.5, cc.v2(0, 480));
            }


            let finished = cc.callFunc(function (target) {
                let action2 = cc.fadeOut(1);
                cc.imgSplit.useless[i].node.runAction(action2);
            })
            let action3 = cc.sequence(action, finished);
            cc.imgSplit.useless[i].node.runAction(action3);

        }

        setTimeout(() => {
            for (let i = 0; i < cc.imgSplit.useless.length; i++) {
                cc.imgSplit.useless[i].node.active = false;
            }
            let wasteArray = [];
            for (let i = 0; i < this.startpuzzle.length; i++) {
                console.log(this.startpuzzle);
                if (Number(this.startpuzzle[i].name) > 48) {
                    console.log("走几次啊");
                    console.log(Number(this.startpuzzle[i].name));
                    wasteArray.push(this.startpuzzle[i]);
                    for (let j = this.startpuzzle.indexOf(this.startpuzzle[i]) + 1; j < this.startpuzzle.length; j++) {
                        console.log(j);
                        this.startpuzzle[j].stopAllActions();
                        let action4 = cc.moveTo(0.15, this.startpos[j - 1]);
                        if (Number(this.startpuzzle[i].name) <= 48) {
                            this.startpuzzle[j].runAction(action4);
                        }
                    }
                    console.log(this.startpuzzle.indexOf(this.startpuzzle[i]));

                }
            }

            for (let i = 0; i < wasteArray.length; i++) {
                this.startpuzzle.splice(this.startpuzzle.indexOf(wasteArray[i]), 1);
            }
            console.log(wasteArray);
            this.content.width -= 200 * wasteArray.length;
            this.content.setPosition(cc.v2(this.content.x, -cc.winSize.height / 2 + this.content.height))
            this.dontOnMask.parent = null;
            this.donContOnMask.parent = null;
        }, 2500);



    },



    // update (dt) {},
});
